package com.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ResourceBundle;

public class DBUtils {
	private static String driver;
	private static String url;
	private static String user;
	private static String password;
	
	public Connection conn ;
	public PreparedStatement pst;
	
	
	static{
		//��ʼ��
//		db��db.properties��ǰ׺
		ResourceBundle rb=ResourceBundle.getBundle("db");
		driver=rb.getString("jdbc.driver");
		url=rb.getString("jdbc.url");
		user=rb.getString("jdbc.username");
		password=rb.getString("jdbc.password");
	}
	
	//��������
	public  DBUtils(){
		try {
			Class.forName(driver);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//������Ӷ���
	public void  getConn(){
		try {
			conn = DriverManager.getConnection(url, user, password);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public int exeUpdate(String sql,Object ... params){
		try {
			getConn();
			pst = conn.prepareStatement(sql);
			if(params!=null){
				for(int i=0;i<params.length;i++){
					pst.setObject(i+1, params[i]);
				}
			}
			//ִ��
			int n = pst.executeUpdate();
			return n;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}
	
	//ִ�в�ѯ
	public ResultSet exeQuery(String sql,Object ...params){
		
		ResultSet rs=null;
		try {
			getConn();
			pst = conn.prepareStatement(sql);
			if(params!=null){
				for(int i=0;i<params.length;i++){
					pst.setObject(i+1, params[i]);
				}
			}
			//ִ��
			return pst.executeQuery();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	
	//�ر�����
	public void closeAll(ResultSet rs,PreparedStatement pst,Connection conn){
		try {
			if(rs!=null){
				rs.close();
			}
			if(pst!=null){
				pst.close();
			}
			if(conn!=null){
				conn.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	
	
	public static void main(String[] args) {
		new DBUtils();
	}
}
